package com.haoqizhe.kernel.redis.common.util;

import com.haoqizhe.kernel.redis.config.RedisCacheConfig;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.AutoConfigureAfter;
import org.springframework.data.redis.core.*;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.io.Serializable;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.TimeUnit;

/**
 * redis util
 *
 * @author haoqizhe.li
 * @date 2018/4/2 21:23
 */
@Slf4j
@Component
@AutoConfigureAfter(RedisCacheConfig.class)
public class RedisUtil {
    @Autowired
    private RedisTemplate redisTemplate;
    @Resource(name = "redisTemplate")
    private ValueOperations operations;
    @Resource(name = "redisTemplate")
    private ListOperations listOperations;
    @Resource(name = "redisTemplate")
    private HashOperations hashOperations;
    @Resource(name = "redisTemplate")
    private SetOperations setOperations;
    @Resource(name = "redisTemplate")
    private ZSetOperations zSetOperations;

    /**
     * 批量删除对应的value
     *
     * @param keys
     */
    public void remove(final String... keys) {
        for (String key : keys) {
            remove(key);
        }
    }

    /**
     * 批量删除key
     *
     * @param pattern
     */
    public void removePattern(final String pattern) {
        Set<Serializable> keys = redisTemplate.keys(pattern);
        if (keys.size() > 0) {
            redisTemplate.delete(keys);
        }
    }

    /**
     * 删除对应的value
     *
     * @param key
     */
    public void remove(final String key) {
        if (exists(key)) {
            redisTemplate.delete(key);
        }
    }

    /**
     * 判断缓存中是否有对应的value
     *
     * @param key
     * @return
     */
    public boolean exists(final String key) {
        return redisTemplate.hasKey(key);
    }

    /**
     * 设置失效时间
     *
     * @param key
     * @param expire 失效时间（单位秒）
     */
    public void expire(final String key, Long expire) {
        redisTemplate.expire(key, expire, TimeUnit.SECONDS);
    }

    /**
     * 移除key的过期时间，持久化key
     *
     * @param key
     */
    public void persist(final String key) {
        redisTemplate.persist(key);
    }

    /**
     * 读取缓存
     *
     * @param key
     * @return
     */
    public Object get(final String key) {
        Object result = operations.get(key);
        return result;
    }

    /**
     * 写入缓存
     *
     * @param key
     * @param value
     * @return
     */
    public boolean set(final String key, Object value) {
        return set(key, value, -1L);
    }

    /**
     * 写入缓存
     *
     * @param key
     * @param value
     * @return
     */
    public boolean set(final String key, Object value, Long expireTime) {
        boolean result = false;
        try {
            operations.set(key, value);
            if (expireTime > 0) {
                redisTemplate.expire(key, expireTime, TimeUnit.SECONDS);
            }
            result = true;
        } catch (Exception e) {
            log.error("写入缓存失败：" + e.getMessage(), e);
        }
        return result;
    }

    /**
     * 获取匹配规则的key集合
     *
     * @param pattern
     * @return
     */
    public Set keys(final String pattern) {
        return redisTemplate.keys(pattern);
    }

    /**
     * 自增
     *
     * @param key
     * @return
     */
    public Long incr(final String key) {
        return incrBy(key, 1);
    }


    /**
     * 带步长的自增
     *
     * @param key
     * @param value
     * @return
     */
    public Long incrBy(final String key, long value) {
        return operations.increment(key, value);
    }


    /**
     * 带步长的自减
     *
     * @param key
     * @param value
     * @return
     */
    public Long decrBy(final String key, long value) {
        return operations.decrement(key, value);
    }

    /**
     * 自减
     *
     * @param key
     * @return
     */
    public Long decr(final String key) {
        return decrBy(key, 1);
    }

    /**
     * 返回key的value的子串
     *
     * @param key
     * @param start
     * @param end
     * @return
     */
    public Object substr(final String key, long start, long end) {
        Object result = null;
        try {
            result = operations.get(key, start, end);
        } catch (Exception e) {
            log.error("获取缓存失败：" + e.getMessage(), e);
        }
        return result;
    }

    /**
     * 给key的value附加内容
     *
     * @param key
     * @param value
     * @return
     */
    public boolean append(final String key, String value) {
        boolean result = false;
        try {
            operations.append(key, value);
            result = true;
        } catch (Exception e) {
            log.error("附加内容失败：" + e.getMessage(), e);
        }
        return result;
    }


    // ------------------------------------------list----------------------------------------------------

    /**
     * 往列表尾部添加元素
     *
     * @param key
     * @param value
     * @return
     */
    public boolean rightPush(final String key, Object value) {
        boolean result = false;
        try {
            listOperations.rightPush(key, value);
            result = true;
        } catch (Exception e) {
            log.error("列表写入缓存失败：" + e.getMessage(), e);
        }
        return result;
    }

    /**
     * 往列表尾部批量添加元素
     *
     * @param key
     * @param list
     * @return
     */
    public long rightPushBacth(final String key, List<?> list) {
        long result = 0;
        try {
            result = listOperations.rightPushAll(key, list);
        } catch (Exception e) {
            log.error("列表批量写入缓存失败：" + e.getMessage(), e);
        }
        return result;
    }

    /**
     * 往列表头部添加元素
     *
     * @param key
     * @param value
     * @return
     */
    public boolean leftPush(final String key, Object value) {
        boolean result = false;
        try {
            listOperations.leftPush(key, value);
            result = true;
        } catch (Exception e) {
            log.error("列表写入缓存失败：" + e.getMessage(), e);
        }
        return result;
    }

    /**
     * 往列表头部批量添加元素
     *
     * @param key
     * @param list
     * @return
     */
    public long leftPushBacth(final String key, List<?> list) {
        long result = 0;
        try {
            result = listOperations.leftPushAll(key, list);
        } catch (Exception e) {
            log.error("列表批量写入缓存失败：" + e.getMessage(), e);
        }
        return result;
    }

    /**
     * 从列表尾部提取元素
     *
     * @param key
     * @return
     */
    public Object rightPop(final String key) {
        Object result = null;
        try {
            result = listOperations.rightPop(key);
        } catch (Exception e) {
            log.error("获取列表尾部元素失败：" + e.getMessage(), e);
        }
        return result;
    }

    /**
     * 从列表头部提取元素
     *
     * @param key
     * @return
     */
    public Object leftPop(final String key) {
        Object result = null;
        try {
            result = listOperations.leftPop(key);
        } catch (Exception e) {
            log.error("获取列表头部元素失败：" + e.getMessage(), e);
        }
        return result;
    }

    /**
     * 返回列表指定索引范围内的元素
     *
     * @param key
     * @param start
     * @param end
     * @return
     */
    public List<?> lrange(final String key, long start, long end) {
        List<?> result = null;
        try {
            result = listOperations.range(key, start, end);
        } catch (Exception e) {
            log.error("获取列表元素失败：" + e.getMessage(), e);
        }
        return result;
    }

    /**
     * 返回列表start位置开始len个元素
     *
     * @param key
     * @param start
     * @param len
     * @return
     */
    public List<?> rangeForLen(final String key, long start, long len) {
        long end = start + len - 1;
        return lrange(key, start, end);
    }

    /**
     * 返回列表长度
     *
     * @param key
     * @return
     */
    public long llen(final String key) {
        long result = 0;
        try {
            result = listOperations.size(key);
        } catch (Exception e) {
            log.error("获取列表长度失败：" + e.getMessage(), e);
        }
        return result;
    }

    /**
     * 设置列表指定元素的值
     *
     * @param key   列表key
     * @param index 指定位置
     * @param value 元素值
     * @return
     */
    public boolean lset(final String key, long index, Object value) {
        boolean result = false;
        try {
            listOperations.set(key, index, value);
            result = true;
        } catch (Exception e) {
            log.error("设置列表元素失败：" + e.getMessage(), e);
        }
        return result;
    }

    /**
     * 设置列表指定位置的元素
     *
     * @param key   列表key
     * @param index 指定位置
     * @return
     */
    public Object lindex(final String key, long index) {
        Object result = null;
        try {
            result = listOperations.index(key, index);
        } catch (Exception e) {
            log.error("获取列表指定元素失败：" + e.getMessage(), e);
        }
        return result;
    }

    /**
     * 将列表从指定位置范围内截取
     *
     * @param key
     * @param start
     * @param end
     * @return
     */
    public boolean ltrim(final String key, long start, long end) {
        boolean result = false;
        try {
            listOperations.trim(key, start, end);
            result = true;
        } catch (Exception e) {
            log.error("截取列表失败：" + e.getMessage(), e);
        }
        return result;
    }

    /**
     * 将列表从指定位置开始截取
     *
     * @param key
     * @param start
     * @param len
     * @return
     */
    public boolean trimForLen(final String key, long start, long len) {
        long end = start + len - 1;
        return ltrim(key, start, end);
    }

    /**
     * 将源列表的尾部元素从源列表中移除，并添加到目标列表的头部
     *
     * @param srcKey
     * @param desKey
     * @return
     */
    public boolean rpoplpush(final String srcKey, final String desKey) {
        boolean result = false;
        try {
            listOperations.rightPopAndLeftPush(srcKey, desKey);
            result = true;
        } catch (Exception e) {
            log.error("列表操作失败：" + e.getMessage(), e);
        }
        return result;
    }

    // --------------------------------------------hash--------------------------------------------------

    /**
     * 将hash表添加到缓存中
     *
     * @param key
     * @param field
     * @param value
     * @return
     */
    public boolean hset(final String key, final String field, Object value) {
        boolean result = false;
        try {
            hashOperations.put(key, field, value);
            result = true;
        } catch (Exception e) {
            log.error("hash添加内容失败：" + e.getMessage(), e);
        }
        return result;
    }

    /**
     * 获取hash表中字段的值
     *
     * @param key
     * @param field
     * @return
     */
    public Object hget(final String key, final String field) {
        Object result = null;
        try {
            result = hashOperations.get(key, field);
        } catch (Exception e) {
            log.error("获取hash内容失败：" + e.getMessage(), e);
        }
        return result;
    }

    /**
     * 获取hash中多个字段值
     *
     * @param key
     * @param fields
     * @return
     */
    public List<Object> hgetbatch(final String key, List<String> fields) {
        List<Object> result = null;
        try {
            result = hashOperations.multiGet(key, fields);
        } catch (Exception e) {
            log.error("批量获取hash内容失败：" + e.getMessage(), e);
        }
        return result;
    }

    /**
     * 批量添加
     *
     * @param key
     * @param fields
     * @return
     */
    public boolean hsetbatch(final String key, Map<String, Object> fields) {
        boolean result = false;
        try {
            hashOperations.putAll(key, fields);
            result = true;
        } catch (Exception e) {
            log.error("批量添加hash内容失败：" + e.getMessage(), e);
        }
        return result;
    }

    /**
     * 判断hash中是否存在指定字段
     *
     * @param key
     * @param field
     * @return
     */
    public boolean hexist(final String key, String field) {
        boolean result = false;
        try {
            result = hashOperations.hasKey(key, field);
        } catch (Exception e) {
            log.error("hash操作失败：" + e.getMessage(), e);
        }
        return result;
    }

    /**
     * 删除hash中指定字段
     *
     * @param key
     * @param fields
     * @return
     */
    public boolean hdel(final String key, String... fields) {
        boolean result = false;
        try {
            hashOperations.delete(key, fields);
            result = true;
        } catch (Exception e) {
            log.error("hash字段删除失败：" + e.getMessage(), e);
        }
        return result;
    }

    /**
     * 获取hash中所有字段
     *
     * @param key
     * @return
     */
    public Set<String> hkeys(final String key) {
        Set<String> result = null;
        try {
            result = hashOperations.keys(key);
        } catch (Exception e) {
            log.error("hash字段获取失败：" + e.getMessage(), e);
        }
        return result;
    }

    /**
     * 获取hash字段数
     *
     * @param key
     * @return
     */
    public Long hlen(final String key) {
        long result = 0;
        try {
            result = hashOperations.size(key);
        } catch (Exception e) {
            log.error("hash长度获取失败：" + e.getMessage(), e);
        }
        return result;
    }

    /**
     * 获取hash所有键值对
     *
     * @param key
     * @return
     */
    public Map<String, Object> hgetall(final String key) {
        Map<String, Object> result = null;
        try {
            result = hashOperations.entries(key);
        } catch (Exception e) {
            log.error("hash键值对获取失败：" + e.getMessage(), e);
        }
        return result;
    }

    // -------------------------------------------set----------------------------------------------------

    public Set sMembers(String key) {
        return setOperations.members(key);
    }

    public Long sAdd(String key, Object... obj) {
        return setOperations.add(key, obj);
    }

    public void sRemove(String key, Object obj) {
        setOperations.remove(key, obj);
    }

    /**
     * 判断元素是否存在集合中
     *
     * @param key
     * @param value
     * @return
     */
    public boolean sIsMember(String key, Object value) {
        return setOperations.isMember(key, value);
    }

    /**
     * 随机返回有序集合中元素（不修改原集合）
     *
     * @param key
     * @return
     */
    public Object sRandomMember(String key) {
        return setOperations.randomMember(key);
    }

    /**
     * 随机返回指定数量的集合元素
     *
     * @param key
     * @return 当count为正数时，返回不重复的元素集合；当count为负数时，返回元素集合可以存在元素重复的情况
     */
    public List<Object> sRandomMembers(String key, int count) {
        return setOperations.randomMembers(key, count);
    }

    // -------------------------------------------zset----------------------------------------------------

    public void zAdd(String key, Double score, Object value) {
        zSetOperations.add(key, value, score);
    }

    /**
     * 批量新增有序集合的元素
     *
     * @param key
     * @param values 集合元素（包括value 和 score）
     */
    public void zAdds(String key, Set values) {
        zSetOperations.add(key, values);
    }

    /**
     * 对有序集合中的元素的score进行修改
     *
     * @param key
     * @param score
     * @param value
     */
    public void zIncr(String key, Double score, Object value) {
        zSetOperations.incrementScore(key, value, score);
    }

    /**
     * 删除有序集合的元素
     *
     * @param key
     * @param value
     */
    public void zRemove(String key, Object value) {
        zSetOperations.remove(key, value);
    }

    /**
     * 获取有序集合的成员数
     *
     * @param key
     */
    public Long zMemberCount(String key) {
        return zSetOperations.zCard(key);
    }

    /**
     * 获取有序集合指定范围的成员
     *
     * @param key
     * @param start
     * @param end
     * @return
     */
    public Set<Object> zRange(String key, int start, int end) {
        return zSetOperations.range(key, start, end);
    }

    /**
     * 获取有序集合指定score范围的成员
     *
     * @param key
     * @param start
     * @param end
     * @return 元素集合
     */
    public Set<Object> zRangeByScore(String key, double start, double end) {
        return zSetOperations.rangeByScore(key, start, end);
    }

    /**
     * 取有序集合指定score范围内指定个数的成员
     *
     * @param key
     * @param min
     * @param max
     * @param offset
     * @param count
     * @return 元素集合
     */
    public Set<Object> zRangeByScore(String key, double min, double max, int offset, int count) {
        return zSetOperations.rangeByScore(key, min, max, offset, count);
    }

    /**
     * 获取有序集合指定score范围的成员
     *
     * @param key
     * @param min
     * @param max
     * @return 元素+score的集合
     */
    public Set<Object> zRangeWithScore(String key, double min, double max) {
        return zSetOperations.rangeByScoreWithScores(key, min, max);
    }

    /**
     * 获取有序集合指定score范围内指定个数的成员
     *
     * @param key
     * @param min
     * @param max
     * @param offset
     * @param count
     * @return 元素+score的集合
     */
    public Set<Object> zRangeWithScore(String key, double min, double max, int offset, int count) {
        return zSetOperations.rangeByScoreWithScores(key, min, max, offset, count);
    }
}
